<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="4" :xs="24">
        <areas :area-type="areaType" :areas="treeAreas" v-on:handleNodeClick="onHandleNodeClick"/>
      </el-col>
      <el-col :span="20" :xs="24">
        <el-card>
          <div class="filter-container">
            <el-select v-model="listQuery.unit" class="filter-item" clearable placeholder="单元号"
                       style="margin-left: 20px;width: 110px">
              <el-option
                v-for="item in units"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
            <el-input v-model="listQuery.floor" class="filter-item" clearable placeholder="楼层"
                      style="margin-left: 10px;width: 120px" type="number"></el-input>
            <el-input v-model="listQuery.room_number" class="filter-item" clearable placeholder="门牌号"
                      style="margin-left: 10px;width: 120px" type="number"></el-input>
            <el-input v-model="listQuery.device_number" class="filter-item" clearable
                      placeholder="终端编号" style="margin-left: 10px;width: 160px"></el-input>
            <el-button v-if="checkPermission('查询设备')" class="filter-item" icon="el-icon-search" style="margin-left:20px"
                       type="primary"
                       @click="getDeviceList">
              查询
            </el-button>
            <el-button v-if="checkPermission('水费配价')" class="filter-item" icon="el-icon-plus" style="margin-left:10px"
                       type="primary"
                       @click="openBatchWindow">
              批量配价
            </el-button>
            <el-button v-if="checkPermission('配价导出')" class="filter-item" icon="el-icon-download" style="margin-left:10px"
                       type="primary"
                       @click="exportPrice">
              导出
            </el-button>
          </div>
          <div class="app-container">
            <el-table
              :key="tableKey"
              ref="price-alloc"
              :loading="listLoading"
              :data="list"
              border
              fit
              highlight-current-row
              stripe
            >
              <el-table-column
                type="selection"
                align="center"
                width="50">
              </el-table-column>
              <el-table-column
                type="index"
                align="center"
                label="#"
                width="50">
              </el-table-column>
              <el-table-column align="left" label="用户">
                <template v-slot="{row}">
                  <span>{{ row.customer ? row.customer.customer_name : '-' }}</span>
                </template>
              </el-table-column>
              <el-table-column align="left" label="地址">
                <template v-slot="{row}">
                  <span>{{ row.install_address }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="终端号">
                <template v-slot="{row}">
                  <span>{{ row.terminal_number }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="配价方案">
                <template v-slot="{row}">
                  <span>{{ priceRateText(row) }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="优惠方案">
                <template v-slot="{row}">
                  <span>{{ discountText(row)}}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="滞纳金方案">
                <template v-slot="{row}">
                  <span>{{ lateFeeText(row) }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="信用额度">
                <template v-slot="{row}">
                  <span>{{ row.credit_limit }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" class-name="small-padding fixed-width" label="操作" width="200">
                <template v-slot="{row,$index}">
                  <el-button v-if="checkPermission('水费配价')" size="mini"  type="primary"
                             @click="updateDevice(row)">
                    配价
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <pagination v-show="total>0" :limit.sync="listQuery.pageSize" :page.sync="listQuery.page" :total="total"
                        @pagination="getDeviceList"/>

            <el-dialog title="配价" :visible.sync="dialogFormVisible"
                       custom-class="window-small-width">
              <el-form ref="priceAllocForm" :model="temp" :rules="form.rules" label-position="right" label-width="80px"
              >
                <el-form-item label="用户" prop="customer_id">
                  {{ temp.customer | customerAddress}}
                </el-form-item>
                <el-form-item label="终端编号" prop="terminal_number">
                  {{temp.terminal_number}}
                </el-form-item>
                <el-form-item label="水司编号" prop="terminal_number">
                  {{temp.terminal_number}}
                </el-form-item>
                <el-form-item label="水费计价" prop="price_config_tpl_id">
                  <el-select v-model="temp.price_config_tpl_id"   placeholder="水费计价">
                    <el-option
                      v-for="item in priceList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="充值优惠" prop="price_discount_id">
                  <el-select v-model="temp.price_discount_id"   placeholder="充值优惠">
                    <el-option
                      v-for="item in discountList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="滞纳金" prop="late_fee_config_id">
                  <el-select v-model="temp.late_fee_config_id"  placeholder="请选择">
                    <el-option
                      v-for="item in lateFeeList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="信用额度" prop="credit_limit">
                  <el-input v-model.number="temp.credit_limit"></el-input>
                </el-form-item>
                <el-form-item label="账单周期" prop="bill_type">
                  <el-select v-model="temp.bill_type"  placeholder="请选择">
                    <el-option
                      v-for="item in [{id:1,name:'日'},{id:2,name:'月'}]"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">
                  取消
                </el-button>
                <el-button :loading="btnLoading" type="primary" @click="handlePriceAlloc">
                  确认
                </el-button>
              </div>
            </el-dialog>
            <el-dialog title="批量配价" :visible.sync="dialogBatchFormVisible"
                       custom-class="window-small-width">
              <el-alert
                title="批量配价将覆盖当前区域的所有设备配价方案，请谨慎操作！"
                type="warning" :closable="false">
              </el-alert>
              <el-form ref="priceAllocBatchForm" :model="batchForm.model" :rules="batchForm.rules" label-position="right" label-width="80px"
              >
                <el-form-item label="区域" prop="area_code">
                  <el-link type="primary">
                    {{ batchForm.model.address}}
                  </el-link>
                </el-form-item>
                <el-form-item label="设备数量" prop="terminal_number">
                  {{ total }}
                </el-form-item>
                <el-form-item label="水费计价" prop="price_config_tpl_id">
                  <el-select v-model="batchForm.model.price_config_tpl_id"   placeholder="水费计价">
                    <el-option
                      v-for="item in priceList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="充值优惠" prop="price_discount_id">
                  <el-select v-model="batchForm.model.price_discount_id"   placeholder="充值优惠">
                    <el-option
                      v-for="item in discountList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="滞纳金" prop="late_fee_config_id">
                  <el-select v-model="batchForm.model.late_fee_config_id"  placeholder="请选择">
                    <el-option
                      v-for="item in lateFeeList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="信用额度" prop="credit_limit">
                  <el-input v-model.number="batchForm.model.credit_limit"></el-input>
                </el-form-item>
                <el-form-item label="账单周期" prop="bill_type">
                  <el-select v-model="batchForm.model.bill_type"  placeholder="请选择">
                    <el-option
                      v-for="item in [{id:1,name:'日'},{id:2,name:'月'}]"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogBatchFormVisible = false">
                  取消
                </el-button>
                <el-button :loading="btnLoading" type="primary" @click="handleBatchPriceAlloc">
                  确认
                </el-button>
              </div>
            </el-dialog>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import areas from '@/components/area/AreaTree'
import Pagination from '@/components/Pagination'
import {
  getDeviceList,
  deviceAllocPrice,
  deviceBatchAllocPrice,
  exportPrice
} from "@/api/device";
import {fetchList as fetchDiscountList} from "@/api/discount";
import {fetchList as fetchLateFeeList} from "@/api/late-fee";
import {fetchList as fetchPriceList} from "@/api/pricing";
import {getAreaTree} from "@/api/area";
import {checkPermission} from "@/utils/permission"
import jsUtils from 'jutils-src'

const unset = {
  id: 0,
  name: '未设置',
}


export default {
  name: 'PriceAlloc',
  components: {Pagination,areas},
  data() {
    const validatePrice = (rule, value, callback) => {
      if (this.temp.price_config_tpl_id === 0) {
        callback(new Error('请选择对应的水费费率'))
      } else {
        callback()
      }
    }
    return {
      dialogFormVisible: false,
      dialogBatchFormVisible: false,
      btnLoading: false,
      tableKey: 0,
      deviceLogs: [],
      reverse: true,
      exportData: [],
      listLoading: true,
      list: [],
      areaType: 2,
      temp:{},
      treeAreas: [],
      priceList: [],
      discountList:[],
      lateFeeList:[],
      total: 0,
      listQuery: {
        area_code: '',
        address: '',
        device_number: '',
        class: '',
        unit: '',
        floor: '',
        room_number: '',
        page: 1,
        pageSize: 20,
      },
      units: ['一单元', '二单元', '三单元', '四单元', '五单元', '六单元', '七单元', '八单元', '九单元', '十单元'],
      form:{
        rules:{
          // price_config_tpl_id: [
          //   {validator: validatePrice, trigger: 'change'}
          // ]
        },
        model:{

        }
      },
      batchForm: {
        rules:{
          // price_config_tpl_id: [
          //   {validator: validatePrice, trigger: 'change'}
          // ]
        },
        model: {
          area_code:null,
          address: null,
          credit_limit: 0,
          price_config_tpl_id: 0,
          price_discount_id: 0,
          late_fee_config_id: 0,
          bill_type:1,
        }
      }
    };
  },
  filters: {
    customerAddress(customer) {
      if(!customer) {
        return '-'
      }
      return  customer.area_name+'/'+customer.unit+'/'+customer.floor+'楼/'+customer.room_number
    }
  },
  created() {
    this.getDeviceList()
    this.getAreaTree()
    this.getPriceList()
    this.getLateFeeList()
    this.getDiscountList()
  },
  methods: {
    checkPermission,
    getAreaTree() {
      getAreaTree({type: 2}).then(response => {
        this.treeAreas = response.data
      })
    },
    onHandleNodeClick: function (data) {
      this.listQuery.area_code = data.code
      this.listQuery.address = data.address
      this.getDeviceList()
    },
    priceRateText(val) {
      return val.price_rate ? val.price_rate.name : '-'
    },
    discountText(val) {
      return val.discount ? val.discount.name : '-'
    },
    lateFeeText(val) {
      return val.late_fee ? val.late_fee.name : '-'
    },
    getDeviceList() {
      this.listLoading = true
      let queryData = Object.assign({}, this.listQuery)
      queryData.device_size = queryData.device_size || 0
      getDeviceList(this.listQuery).then(response => {
        this.list = response.data.list
        this.total = response.data.total
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    getPriceList() {
      fetchPriceList({status:1,pageSize: 9999}).then(resp => {
        this.priceList = resp.data.list
        this.priceList.unshift(unset)
      })
    },
    getDiscountList() {
      fetchDiscountList({status:1,pageSize: 9999}).then(resp => {
        this.discountList = resp.data.list
        this.discountList.unshift(unset)
      })
    },
    getLateFeeList() {
      fetchLateFeeList({status:1,pageSize: 9999}).then(resp => {
        this.lateFeeList = resp.data.list
        this.lateFeeList.unshift(unset)
      })
    },
    updateDevice(row) {
      this.resetTemp()
      this.dialogStatus = 'update'
      this.temp = Object.assign({}, row)
      if(this.temp.bill_type === 0) {
        this.temp.bill_type = 1
      }
      this.dialogFormVisible = true
    },
    handlePriceAlloc() {
      this.$refs['priceAllocForm'].validate((valid) => {
        if (valid) {
          deviceAllocPrice(this.temp).then(resp => {
            if(resp.code === 20000) {
              this.$message({
                message: '配价完成',
                type: 'success'
              })
              this.dialogFormVisible = false
              this.getDeviceList()
            }
          })
        }
      })
    },
    openBatchWindow(){
      if(this.listQuery.area_code.length === 0) {
        this.$message.warning('请选择区域')
        return
      }
      if(this.total === 0) {
        this.$message.warning('所选区域没有设备')
        return
      }
      this.$nextTick(() => {
        this.batchForm.model = Object.assign({}, {
          area_code: this.listQuery.area_code,
          address: this.listQuery.address,
          price_config_tpl_id: 0,
          price_discount_id: 0,
          late_fee_config_id: 0,
          bill_type:1,
        })
      })
      this.dialogBatchFormVisible = true
    },
    handleBatchPriceAlloc() {
      this.$refs['priceAllocBatchForm'].validate((valid) => {
        if(valid) {
          deviceBatchAllocPrice(this.batchForm.model).then(resp => {
            if(resp.code === 20000) {
              this.$message({
                message: '配价完成',
                type: 'success'
              })
              this.dialogBatchFormVisible = false
              this.getDeviceList()
            }
          })
        }
      })
    },
    exportPrice() {
      if(this.total > 5000 ) {
        this.$confirm('设备数据过大，导出时间可能较长确定要导出吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.handleExport()
        })
      }else {
        this.handleExport()
      }
    },
    handleExport() {
      exportPrice(this.listQuery).then(resp => {
        const url = window.URL.createObjectURL(new Blob([resp.data]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', '设备配价信息.xlsx'); // 设置下载文件名
        document.body.appendChild(link);
        link.click();
        link.remove(); // 下载后移除元素
      })
    },
    formatDate(dateStr) {
      return jsUtils.formatDate(new Date(dateStr), 'YYYY-MM-DD')
    },
    resetTemp() {
      this.temp = {
        id: 0,
        area_code: '',
        area_name: '',
        area_path: '',
        class: '',
        version: '1.1',
        name: "",
        customer_id: '',
        size: 15,
        install_address: '',
        install_date: '',
        start_amount: 0,
        status: 0,
        terminal_number: ''
      }
    },
    resetQueryParams() {
      this.listQuery = {
        id: 0,
        page: 1,
        pageSize: 20,
        name: ''
      }
    }
  }
}
</script>
